package org.example.Day13;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyUtil {
    public static UserService createProxy(UserService userService){
        UserService userServiceProxy
                =(UserService) Proxy.newProxyInstance(
                ProxyUtil.class.getClassLoader(),
                new Class[]{UserService.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if(
                                method.getName().equals("login") ||
                                method.getName().equals("deleteUsers")||
                                method.getName().equals("selectUsers")
                        ){
                            //方法运行前记录毫秒值
                            long startTime = System.currentTimeMillis();
                            //执行方法
                            Object rs = method.invoke(userService,args);
                            //执行方法后记录毫秒值
                            long endtime = System.currentTimeMillis();
                            System.out.println(method.getName()+"方法执行耗时:"+(endtime-startTime)/1000.0+"s");
                            return rs;
                        }else{
                            Object rs = method.invoke(userService,args);
                            return rs;
                        }

                    }
                }
        );
        return userServiceProxy;
    }
}
